﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace PyNet
{
    static class clsAuth
    {
        public static void CheckDirectory()
        {
            clsFileSystem.CheckDir("Auth");
        }

        public static clsAuthNote GetAuth(string name)
        {
            CheckDirectory();
            clsAuthNote note = new clsAuthNote();
            note.name = name.ToLower();
            BinaryReader bin;
            try
            {
                 bin = new BinaryReader(File.Open("Auth/" + note.name + ".bin", FileMode.Open));
            } catch (FileNotFoundException e) {
                note.exists = false;
                Program.GetLogger.Write("DarkGreen", "File not found: " + name.ToLower() + ".bin");
                return note;
            }

            note.auth = new byte[20];
            bin.Read(note.auth, 0, 20);
            note.exists = true;

            for (int i = 0; i < note.auth.Length; )
            {
                if (note.auth[i] != 0xFF)
                    note.banned = false;
                i++;
            }

            bin.Close();

            Program.GetLogger.Write("DarkGreen", "Read auth binary file for '" + name.ToLower() + "'.");

            return note;
        }

        public static bool SetAuth(string name, byte[] auth)
        {
            CheckDirectory();
            clsAuthNote note = GetAuth(name.ToLower());
            if (!note.exists)
            {
                BinaryWriter bin = new BinaryWriter(File.Open("Auth/" + name.ToLower() + ".bin", FileMode.OpenOrCreate));
                bin.Write(auth);
                bin.Close();
                Program.GetLogger.Write("DarkGreen", "Created auth binary file for '" + name.ToLower() + "'.");
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool CheckAuth(byte[] a, byte[] b)
        {
            if (a.Length != b.Length) return false;

            for (int i = 0; i < a.Length; )
            {
                if (a[i] != b[i])
                    return false;
                i++;
            }

            return true;
        }
    }

    class clsAuthNote
    {
        public string name;
        public byte[] auth;
        public bool exists = false;
        public bool banned = true;
    }
}
